import { checkArg } from "../utils/check";
import { DBMgr } from "./db";


export class SunchartModule{
    static ins:SunchartModule;

    async loadByName(argv:{uname:string}){
        let found = await DBMgr.ins.prisma.t_sunchart.findFirst({
            where:{uname:argv.uname}
        })

        return found;
    }

    async save(argv:{
        uname:string,
        chapter:string,
        val1:string,
        val2:string,
        val3:string,
        val4:string,
        val5:string,
    }){
        if(checkArg(argv,"uname","chapter","val1","val2","val3","val4","val5")){
            return "INVALID_PARAMETER";
        }
        
        let result = await this.loadByName(argv);
        let chapter = argv.chapter||"天河永丰";

        let user = await DBMgr.ins.prisma.t_user.findFirst({
            "where":{
                "chapter":chapter,
                "uname":argv.uname
            }
        })

        if(!user){
            user = await DBMgr.ins.prisma.t_user.create({
                "data":{
                    "chapter":chapter,
                    "uname":argv.uname
                }
            })
        }

        if(result){
            await DBMgr.ins.prisma.t_sunchart.update({
                "where":{id:result.id},
                "data":{
                    "uname":argv.uname,
                    "val1":argv.val1,
                    "val2":argv.val2,
                    "val3":argv.val3,
                    "val4":argv.val4,
                    "val5":argv.val5
                }
            })
        }else{
            let createResult = await DBMgr.ins.prisma.t_sunchart.create({
                "data":{
                    "uid":user.id,
                    "uname":argv.uname,
                    "val1":argv.val1,
                    "val2":argv.val2,
                    "val3":argv.val3,
                    "val4":argv.val4,
                    "val5":argv.val5
                }
            })
            return createResult
        }
    }

}

SunchartModule.ins = new SunchartModule()